package com.nuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 
 * 鹦鹉学舌
 * 
 * 
 * 
 * @author admin
 *
 */

public class ChatServer2 {
	public static void main(String[] args) {
		// 设置服务器的监听端口，启动服务器监听

		int port = 8888;

		ServerSocket serverSocket = null;
		Socket socket = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		try {
			// 1.启动服务器监听
			serverSocket = new ServerSocket(port);
			System.out.println("服务器启动成功，请使用客户端进行连接");
			// 2.等待客户端进行连接
			socket = serverSocket.accept();
			System.out.println("客户端连接成功");
			// 3.客户端连接后打开输入流（准备从客户端读取输入）
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			// 4.读取客户端发送过来的数据；

			boolean chatting = true;
			while (chatting) {
				byte[] buffer = new byte[512];
				// 等待客户端发送数据并接收--有阻塞的作用
				int len = inputStream.read(buffer);
				// 5.对数据进行处理
				String string = new String(buffer, 0, len);
				System.out.println(string);
				outputStream.write(("parrot :" + string).getBytes());
				//网络通信需要有一方发起结束通信请求，另一方需要接受退出请求，并进行正常退出
				if ("quit".equalsIgnoreCase(string.trim())) {
					chatting = false;
				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 6.关闭输入流
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (serverSocket != null) {
				try {
					serverSocket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
